package com.irdstudio.efp.nls.service.impl.sx;

import com.alibaba.fastjson.JSONObject;
import com.gdrcu.efp.cus.common.CusBankRelEnum;
import com.gdrcu.efp.cus.common.CusStatusEnum;
import com.gdrcu.efp.cus.common.CusTypeEnum;
import com.irdstudio.basic.framework.core.constant.DateFormatConstant;
import com.irdstudio.basic.framework.core.constant.SDicToExternalConstant;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.threadpool.ApplicationThreadPool2;
import com.irdstudio.basic.framework.core.util.RandomCodeUtils;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.basic.framework.core.util.ValidationUtils;
import com.irdstudio.basic.framework.core.util.sdic.SDicToExternal;
import com.irdstudio.basic.sequence.service.DefaultPatternDescriptor;
import com.irdstudio.basic.sequence.service.PatternDescriptor;
import com.irdstudio.basic.sequence.service.facade.PatternedLimitableSeqService;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.console.service.facade.PrdInfoService;
import com.irdstudio.efp.console.service.vo.KubUserVO;
import com.irdstudio.efp.console.service.vo.PrdInfoVO;
import com.irdstudio.efp.cus.service.facade.*;
import com.irdstudio.efp.cus.service.vo.*;
import com.irdstudio.efp.esb.common.constant.ESBClientConstance;
import com.irdstudio.efp.esb.common.constant.InstitutionEnums;
import com.irdstudio.efp.esb.common.constant.MsLoanConstant;
import com.irdstudio.efp.esb.common.constant.nls.NlsCrrEnum;
import com.irdstudio.efp.esb.service.bo.req.hj.ReqCusInfoCreBean;
import com.irdstudio.efp.esb.service.bo.resp.hj.RespCusInfoCreBean;
import com.irdstudio.efp.esb.service.facade.hj.CustomerInfoCreateService;
import com.irdstudio.efp.nls.common.constant.yed.YedCommonConstant;
import com.irdstudio.efp.nls.common.util.KafkaUtil;
import com.irdstudio.efp.nls.service.facade.NlsApplyRelationService;
import com.irdstudio.efp.nls.service.facade.NlsStageInfoService;
import com.irdstudio.efp.nls.service.facade.queue.NlsProcessRuleService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoExdService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.vo.NlsCreditInfoNoticeVO;
import com.irdstudio.efp.nls.service.vo.NlsStageInfoVO;
import com.irdstudio.efp.nls.service.vo.queue.NlsProcessBizVO;
import com.irdstudio.efp.nls.service.vo.queue.NlsProcessRuleVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoExdVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import com.irdstudio.efp.rule.common.enumeration.RefuseType;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.irdstudio.basic.sequence.service.DefaultPatternDescriptor.*;

/**
 * 需求编号：优e贷<br/>
 * 问题编号：<br/>
 * 功能描述：<br/>
 * 开发人员：dengqiwen<br/>
 * 创建时间：2020/7/30 19:42
 */

@Service("yedCreditCusCreateService")
public class YedCreditCusCreateServiceImpl extends CreditSoltServiceImpl {

    private static Logger log = LoggerFactory.getLogger(YedCreditCusCreateServiceImpl.class);

    @Autowired
    @Qualifier("nlsProcessRuleService")
    private NlsProcessRuleService nlsProcessRuleService;

    @Autowired
    @Qualifier("cusIndivExtService")
    private CusIndivExtService cusIndivExtService;

    @Autowired
    @Qualifier("applicationThreadPool")
    private ApplicationThreadPool2 threadPool;

    @Autowired
    @Qualifier("nlsStageInfoService")
    private NlsStageInfoService nlsStageInfoService;

    @Autowired
    @Qualifier("cusReferrerInfoService")
    private CusReferrerInfoService cusReferrerInfoService;

    @Autowired
    @Qualifier("nlsCreditInfoExdService")
    private NlsCreditInfoExdService nlsCreditInfoExdService;


    // kafka主机IP地址
    @Value("${risk.kafkaServers}")
    private String kafkaServers;

    // kafka发送的主题topic
    @Value("${risk.kafkaToptic}")
    private String kafkaToptic;

    // 日志ID
    private static final String LOGGER_ID = "授信——优e贷客户建档插槽";

    private static final DateTimeFormatter timeStrFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    public static final PatternDescriptor PATTERN =
            DefaultPatternDescriptor.of("CREL" + YEAR_4 + MONTH + DAY + SEQ, 8);
    private static final String other = "Other";

    @Override
    public void doExecute(NlsProcessBizVO nlsProcessBizVo, NlsCreditInfoVO nlsCreditInfoVO) throws Exception {
        String applySeq = nlsProcessBizVo.getApplySeq();
        try {
            log.info(LOGGER_ID+"开始进行优e贷客户建档插槽,流水号:" + applySeq);
            Objects.requireNonNull(nlsCreditInfoVO);

            /** 去互金开户， 如果网贷存在该客户信息则不开户 **/
            String cusId = cusIndivService.getCusIdByCertCode(nlsCreditInfoVO.getCertType(), nlsCreditInfoVO.getCertCode());
            //查授信拓展表
            NlsCreditInfoExdVO pojo=new NlsCreditInfoExdVO();
            pojo.setLmtApplySeq(nlsCreditInfoVO.getLmtApplySeq());
            NlsCreditInfoExdVO nlsCreditInfoExdVO = nlsCreditInfoExdService.queryByPk(pojo);
            CusReferrerInfoVO cusReferrerInfo = getCusReferrerInfo(nlsCreditInfoVO);
            // 更新客户信息-客户编号赋值互金客户建档返回的用户号
            String usrID = "";
            boolean cusIndivExsit = true;
            try {
                if (cusId == null) {
                    log.info(LOGGER_ID+ "网贷不存在该客户，前往互金建档");
                    ReqCusInfoCreBean reqCusInfoCreBean = new ReqCusInfoCreBean();
                    // 客户姓名
                    reqCusInfoCreBean.setCustNm(nlsCreditInfoVO.getCusName());
                    //客户性别
                    reqCusInfoCreBean.setUserGnd(nlsCreditInfoVO.getGender());
                    // 证件类型
                    reqCusInfoCreBean.setCertTp(nlsCreditInfoVO.getCertType());
                    // 证件号码
                    reqCusInfoCreBean.setCertNo(nlsCreditInfoVO.getCertCode());
                    // 签发机关（默认中国）
                    reqCusInfoCreBean.setIssueOrgNm(ConsoleConstant.CHINA);
                    // 手机号码
                    reqCusInfoCreBean.setMblNo(nlsCreditInfoVO.getIndivMobile());
                    // 联系地址
                    reqCusInfoCreBean.setCtcAddr(StringUtil.replaceNullByObj(nlsCreditInfoVO.getIndivRsdAddr()));
                    //居住状况  住宅性质
                    reqCusInfoCreBean.setRsdntlTp(StringUtil.replaceNullByObj(nlsCreditInfoExdVO.getIndivRsdSt()));
                    // 民族
                    reqCusInfoCreBean.setEthnic(StringUtil.replaceNullByObj(nlsCreditInfoVO.getEthnic()));
                    // 客户英文名称
                    reqCusInfoCreBean.setClntEnNm("");
                    // 发证机关地区码
                    reqCusInfoCreBean.setIssueOrgAddrCd("");
                    // 最高学历
                    reqCusInfoCreBean.setHighEdu(StringUtil.replaceNullByObj(nlsCreditInfoVO.getEdu()));
                    //学位
                    reqCusInfoCreBean.setHghstDgr(StringUtil.replaceNullByObj(nlsCreditInfoExdVO.getIndivDgr()));
                    // 国籍
                    reqCusInfoCreBean.setNation(nlsCreditInfoVO.getNational());
                    //行业
                    reqCusInfoCreBean.setIndusCd(StringUtil.replaceNullByObj(nlsCreditInfoVO.getIndivComFld()));
                    //职业
                    try {
                        reqCusInfoCreBean.setCrrCd(StringUtils.isBlank(nlsCreditInfoVO.getProfession()) ? NlsCrrEnum.UNKNOWN.getValue() :
                                (SDicToExternal.getExternalSysDicVal(SDicToExternalConstant.SYSID_IFP, SDicToExternalConstant.CRR, nlsCreditInfoVO.getProfession())));
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("本地系统字典项转互金接口所需字典项出错，请核查配置文件(dicExternal.properties)！");
                    }

                    // 职称
                    reqCusInfoCreBean.setTtl(StringUtil.replaceNullByObj(nlsCreditInfoVO.getTtl()));
                    //职务
                    reqCusInfoCreBean.setPosCd(StringUtil.replaceNullByObj(nlsCreditInfoVO.getIndivComJobTtl()));
                    // 出生日期
                    reqCusInfoCreBean.setBrthDt("");
                    // 工作单位名称
                    reqCusInfoCreBean.setWrkCorpNm(StringUtil.replaceNullByObj(nlsCreditInfoVO.getWrkCorpNm()));
                    // 工作单位地址
                    reqCusInfoCreBean.setWrkCorpAddr(StringUtil.replaceNullByObj(nlsCreditInfoVO.getWrkCorpAddr()));
                    // 工作单位电话
                    reqCusInfoCreBean.setWrkCorpTel("");
                    // 家庭地址
                    reqCusInfoCreBean.setFamAddr("");
                    // 家庭电话
                    reqCusInfoCreBean.setFamTelNo("");
                    // 个人月收入
                    reqCusInfoCreBean.setIndvIncmAmt("");
                    // 家庭月收入
                    reqCusInfoCreBean.setFamIncmAmt("");
                    // 婚姻状况
                    reqCusInfoCreBean.setMrgSitu(StringUtil.replaceNullByObj(nlsCreditInfoVO.getMrgSitu()));
                    // 配偶姓名
                    reqCusInfoCreBean.setSpsNm(StringUtil.replaceNullByObj(nlsCreditInfoVO.getSpsNm()));
                    // 户籍地址
                    reqCusInfoCreBean.setDomcAddr(StringUtil.replaceNullByObj(nlsCreditInfoVO.getCertAddr()));
                    // 配偶联系电话
                    reqCusInfoCreBean.setSpsCtcTelNo("");
                    // 配偶移动电话
                    reqCusInfoCreBean.setSpsMblTelNo("");
                    // 配偶客户号
                    reqCusInfoCreBean.setSpsCustNo("");
                    // 邮编
                    reqCusInfoCreBean.setPstcd(StringUtil.replaceNullByObj(nlsCreditInfoVO.getPostCode()));
                    // 单位性质
                    reqCusInfoCreBean.setCorpChar("");
                    // 是否农户
                    reqCusInfoCreBean.setWhthrFrmr("");
                    //证件到期日
                    reqCusInfoCreBean.setIdenEfftDt(nlsCreditInfoVO.getCertEndDt().replaceAll("-",""));
                    //紧急联系人
                    reqCusInfoCreBean.setUrgntCtcAddr(nlsCreditInfoExdVO.getEmergencyContactName());
                    //紧急联系人号码
                    reqCusInfoCreBean.setUrgntCtcTelNo(nlsCreditInfoExdVO.getEmergencyContactPhone());
                    if(Objects.nonNull(cusReferrerInfo)){
                        reqCusInfoCreBean.setInstId(StringUtils.isEmpty(cusReferrerInfo.getChargeOffBrId())?InstitutionEnums.InstitutionEnum.ZHYYB.getCode():cusReferrerInfo.getChargeOffBrId());
                        //推荐人工号
                        reqCusInfoCreBean.setRefrId(cusReferrerInfo.getReferrerId());
                        //机构代码 -管户机构
                        reqCusInfoCreBean.setBrchCd(cusReferrerInfo.getMainBrId());
                    }
                    // 产品类型  【需求变更】 @date 2019/06/27
                    reqCusInfoCreBean.setProdType(SDicToExternal.getExternalSysDicVal(SDicToExternalConstant.SYSID_IFP, SDicToExternalConstant.PRD_TYPE, nlsCreditInfoVO.getPrdId()));
                    RespCusInfoCreBean respCusInfoCreBean = customerInfoCreateService.customerInfoCreate(reqCusInfoCreBean);
                    cusId = respCusInfoCreBean.getClntNo();
                    // 互金客户建档-用户号
                    usrID = respCusInfoCreBean.getUsrID();
                    cusIndivExsit = false;
                } else {
                    log.info(LOGGER_ID+ "网贷已存在该客户，客户号：" + cusId);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error(LOGGER_ID+"优e贷调用互金核心客户建档异常，信息：" + e.getMessage());
                nlsProcessBizVo.setRefuseMsg(RefuseType.OTHER.getMsg());
                throw new BizException("优e贷调用互金核心客户建档异常", e);
            }
            String prdId = Objects.requireNonNull(nlsCreditInfoVO.getPrdId());
            PrdInfoVO prdInfoVo = new PrdInfoVO();
            prdInfoVo.setPrdId(prdId);
            prdInfoVo = prdInfoService.queryByPk(prdInfoVo);

            final String dateString = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
            final String dateTimeString = LocalDateTime.now().format(timeStrFormatter);
            final String createUser = "admin";

            /** 新增客户信息(如果不存在该客户信息) **/
            final CusIndivVO cusIndivVO = new CusIndivVO();

            cusIndivVO.setCusName(nlsCreditInfoVO.getCusName());
            cusIndivVO.setIndivSex(nlsCreditInfoVO.getGender());
            cusIndivVO.setCertType(nlsCreditInfoVO.getCertType());
            cusIndivVO.setCertCode(nlsCreditInfoVO.getCertCode());
            cusIndivVO.setPhone(nlsCreditInfoVO.getIndivMobile());
            cusIndivVO.setCusType(CusTypeEnum.NATURAL_MAN.getCode());
            cusIndivVO.setCusBankRel(CusBankRelEnum.NORMAL.getCode());
            cusIndivVO.setIndivHouhRegAdd(nlsCreditInfoVO.getCertAddr());
            cusIndivVO.setCusStatus(CusStatusEnum.OFFICIAL.getCode());
            // 民族
            cusIndivVO.setIndivNtn(nlsCreditInfoVO.getEthnic());
            // 国籍
            cusIndivVO.setIndivCountry(nlsCreditInfoVO.getNational());
            // 学历
            cusIndivVO.setIndivEdt(nlsCreditInfoVO.getEdu());
            //学位
            cusIndivVO.setIndivDgr(nlsCreditInfoExdVO.getIndivDgr());
            //居住状况
            cusIndivVO.setIndivRsdSt(nlsCreditInfoExdVO.getIndivRsdSt());
            // 工作单位名称
            cusIndivVO.setIndivComName(nlsCreditInfoVO.getWrkCorpNm());
            //单位性质
            if (!StringUtil.isNullorBank(nlsCreditInfoVO.getWrkCorpNm())){
                //根据企业名称查询企业性质
                CompanyWhiteListVO companyWhiteListVO = new CompanyWhiteListVO();
                companyWhiteListVO.setCompanyName(nlsCreditInfoVO.getWrkCorpNm());
                List<CompanyWhiteListVO> companyWhiteListVOS = companyWhiteListService.queryConditions(companyWhiteListVO);
                if (Objects.nonNull(companyWhiteListVOS) && companyWhiteListVOS.size()>0){
                    cusIndivVO.setIndivComTyp(companyWhiteListVOS.get(0).getCompanyType());
                }
            }
            // 工作单位地址
            cusIndivVO.setIndivComAddr(nlsCreditInfoVO.getWrkCorpAddr());
            // 配偶姓名
            cusIndivVO.setIndivSpsName(nlsCreditInfoVO.getSpsNm());
            // 职称
            cusIndivVO.setIndivCrtfctn(nlsCreditInfoVO.getTtl());
            // 职业
            cusIndivVO.setIndivOcc(nlsCreditInfoVO.getProfession());
            //职务
            cusIndivVO.setIndivComJobTtl(nlsCreditInfoVO.getIndivComJobTtl());
            // 户籍地址
            cusIndivVO.setIndivHouhRegAdd(nlsCreditInfoVO.getCertAddr());
            // 居住地址
            cusIndivVO.setIndivRsdAddr(nlsCreditInfoVO.getIndivRsdAddr());
            //家庭地址 征信报送需要
            cusIndivVO.setFamilyAddr(nlsCreditInfoVO.getIndivRsdAddr());
            // 通讯地址
            cusIndivVO.setPostAddr(nlsCreditInfoVO.getIndivRsdAddr());
            // 首次申请渠道
            cusIndivVO.setFstAppChannel(prdInfoVo.getPrdType());
            //证件到期日
            cusIndivVO.setIndivIdExpDt(nlsCreditInfoVO.getCertEndDt().replaceAll("-",""));
            // 婚姻状况
            cusIndivVO.setIndivMarSt(nlsCreditInfoVO.getMrgSitu());
            //生日
            cusIndivVO.setIndivDtOfBirth(ValidationUtils.getBirthdayFromIdNumber(nlsCreditInfoVO.getCertCode()));
            //家庭地址邮编
            cusIndivVO.setIndivZipCode(nlsCreditInfoVO.getPostCode());
            // 邮政编码
            cusIndivVO.setPostCode(nlsCreditInfoVO.getPostCode());
             //行业
            cusIndivVO.setIndivComFld(nlsCreditInfoVO.getIndivComFld());
            cusIndivVO.setInputId(createUser);
            //客户表的客户经理跟绩效所属人都落推荐人表的推荐人工号，客户表的绩效所属机构落推荐人表的管户机构
            if(Objects.nonNull(cusReferrerInfo)){
                //客户经理
                cusIndivVO.setCusManager(cusReferrerInfo.getReferrerId());
                //绩效所属人
                cusIndivVO.setPerformanceOwner(cusReferrerInfo.getReferrerId());
                //绩效所属机构
                cusIndivVO.setPerformanceOrg(cusReferrerInfo.getMainBrId());
                //网贷经办人落推荐人工号字段 -bf
                nlsCreditInfoVO.setNlsOperUserid(cusReferrerInfo.getReferrerId());
                //网贷经办机构
                nlsCreditInfoVO.setNlsOperOrgid(cusReferrerInfo.getMainBrId());
            }
            cusIndivVO.setLastUpdateTime(dateTimeString);
            cusIndivVO.setLastUpdateUser(createUser);
            //落客户联系人信息表
            CusIndivRelVO cusIndivRelVO = new CusIndivRelVO();
            //新增紧急联系人进客户关系人表

            //紧急联系人姓名
            cusIndivRelVO.setRelName(nlsCreditInfoExdVO.getEmergencyContactName());
            //紧急联系人关系
            cusIndivRelVO.setRelation(nlsCreditInfoExdVO.getEmergencyContactRelate());
            //紧急联系人手机号
            cusIndivRelVO.setMobile(nlsCreditInfoExdVO.getEmergencyContactPhone());
            cusIndivRelVO.setLastUpdateTime(dateTimeString);

            if (cusIndivExsit) {
                cusIndivVO.setCusId(cusId);
                cusIndivRelVO.setCusId(cusId);
                int num1 = cusIndivService.updateByPk(cusIndivVO);
                /** 更新授信申请表 */

                nlsCreditInfoVO.setCusId(cusId);
                nlsCreditInfoService.updateByPk(nlsCreditInfoVO);

                //查询当前客户存量客户联系人
                List<CusIndivRelVO> cusIndivRelVOs = Optional.ofNullable(cusIndivRelService.queryByPkCusId(cusIndivRelVO)).orElseGet(ArrayList::new);
                //如果存在存量联系人，则循环对比，不存在联系人则直接插入
                String relSerno = "";
                if (cusIndivRelVOs.size() > 0) {
                    boolean cusRelExits=Boolean.TRUE;
                    for (CusIndivRelVO cus : cusIndivRelVOs) {
                        //姓名相同则更新,姓名不同则插入
                        if (cus.getRelName().equals(nlsCreditInfoExdVO.getEmergencyContactName())) {
                            cusIndivRelVO.setRelSerno(cus.getRelSerno());
                            cusIndivRelService.updateByPk(cusIndivRelVO);
                            cusRelExits=Boolean.FALSE;
                            break;
                        }
                    }
                    if(cusRelExits) {
                        try {
                            relSerno = sequenceService.getPatternedSequence("CUS_REL_SERNO", PATTERN);
                        } catch (Exception e) {
                            throw new BizException("关系人流水号生成失败");
                        }
                        cusIndivRelVO.setRelSerno(relSerno);
                        cusIndivRelVO.setCreateTime(dateTimeString);
                        cusIndivRelService.insertCusIndivRel(cusIndivRelVO);
                        //kafka异步送数据给风控
                        sendCusIndivRelToRisk(cusIndivRelVO, nlsCreditInfoVO);
                    }
                } else {
                    try {
                        relSerno = sequenceService.getPatternedSequence("CUS_REL_SERNO", PATTERN);
                    } catch (Exception e) {
                        throw new BizException("关系人流水号生成失败");
                    }
                    cusIndivRelVO.setRelSerno(relSerno);
                    cusIndivRelVO.setCreateTime(dateTimeString);
                    cusIndivRelVO.setLastUpdateTime(dateTimeString);
                    cusIndivRelService.insertCusIndivRel(cusIndivRelVO);
                    //kafka异步送数据给风控
                    sendCusIndivRelToRisk(cusIndivRelVO, nlsCreditInfoVO);
                }

                if (num1 == -1) {
                    throw new BizException("客户数据表更新异常!");
                }
            } else {
                nlsProcessBizVo.setCusId(usrID);

                cusIndivVO.setCusId(usrID);
                cusIndivVO.setInnerCusId(cusId);
                cusIndivVO.setComInitLoanDate(dateString);
                cusIndivVO.setInputDate(dateString);
                cusIndivVO.setCreateTime(dateTimeString);
                int num2 = cusIndivService.insertCusIndiv(cusIndivVO);

                /** 更新授信申请表 */
                nlsCreditInfoVO.setCusId(usrID);
                nlsCreditInfoService.updateByPk(nlsCreditInfoVO);

                cusIndivRelVO.setCusId(usrID);
                cusIndivRelVO.setRelSerno(sequenceService.getPatternedSequence("CUS_REL_SERNO", PATTERN));
                cusIndivRelVO.setCreateTime(dateTimeString);
                int num3 = cusIndivRelService.insertCusIndivRel(cusIndivRelVO);

                if (num2 == -1 || num3 == -1) {
                    throw new BizException("客户数据表增加异常!");
                }
                //kafka异步送数据给风控
                sendCusIndivToRisk(cusIndivVO, nlsCreditInfoVO);
                sendCusIndivRelToRisk(cusIndivRelVO, nlsCreditInfoVO);
            }




        } catch (Exception e) {
            e.printStackTrace();
            log.error(LOGGER_ID+ "优e贷客户建档插槽执行失败，异常信息为：" + e.getMessage());
            /** 设置审批状态信息为拒绝 **/
            nlsCreditInfoVO.setApprvSts(MsLoanConstant.NlsApplyStateEnum.REJECT.getVALUE());
            nlsCreditInfoVO.setRefuseCause(e.getMessage());
            sendToRisk(nlsCreditInfoVO);
            nlsProcessBizVo.setExceptionFlag(true);
            nlsProcessBizVo.setExceptionMsg(e);
        }
    }

    private void sendCusIndivRelToRisk(CusIndivRelVO cusIndivRelVO, NlsCreditInfoVO nlsCreditInfoVO) {
        // 授信申请流水号
        String applySeq = nlsCreditInfoVO.getLmtApplySeq();
        log.info("优e贷客户建档，发送 客户联系人信息表 kafka消息给大数据开始执行,流水号:" + applySeq);
        try {
            boolean flag = false;
            //查询开关
            List<NlsStageInfoVO> infoVOS = nlsStageInfoService.queryList();
            for(NlsStageInfoVO vo:infoVOS){
                if(vo.getPrdId().equals("11110004") && vo.getStatus().equals("on") && vo.getStage().equals("credit")){
                    flag = true;
                }
            }
            JSONObject jsonObject = new JSONObject();
            CusIndivRelNoticeVO cusIndivRelNoticeVO = new CusIndivRelNoticeVO();
            cusIndivRelNoticeVO.setTableName("CUS_INDIV_REL");
            cusIndivRelNoticeVO.setCusId(cusIndivRelVO.getCusId());
            cusIndivRelNoticeVO.setRelName(cusIndivRelVO.getRelName());
            cusIndivRelNoticeVO.setRelation(cusIndivRelVO.getRelation());
            cusIndivRelNoticeVO.setMobile(cusIndivRelVO.getMobile());
            cusIndivRelNoticeVO.setCreateTime(cusIndivRelVO.getCreateTime());
            //数据日期
            String timeStamp = TimeUtil.getTimeStampByPattern("yyyy-MM-dd HH:mm:ss");
            cusIndivRelNoticeVO.setDataTime(timeStamp);

            KafkaNoticeHeader header = new KafkaNoticeHeader();
            header.setMessageCode("YED_JISHI");
            header.setTimestamp(timeStamp);
            header.setTransactionId(getTransactionId());
            header.setSysName("netLoan");

            jsonObject.put("head", header);
            jsonObject.put("biz", cusIndivRelNoticeVO);
            if(!flag){
                log.info("实时采集开关未打开！！！");
                return;
            }
            threadPool.add(() -> {
                KafkaUtil kafkaUtil = new KafkaUtil(kafkaServers, kafkaToptic);
                try {
                    kafkaUtil.sendMessage(JSONObject.toJSONString(jsonObject));
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("优e贷客户建档，发送 客户联系人信息表 kafka消息给大数据失败，流水号：" + applySeq + ",异常信息：" + e.getMessage());
                }
            });
        } catch (Exception e) {
            log.info("优e贷客户建档，发送 客户联系人信息表 kafka消息给大数据异常，流水号：" + applySeq + ",异常信息：" + e.getMessage());
        } finally {
            log.info("优e贷客户建档，发送 客户联系人信息表 kafka消息给大数据结束，申请流水号：" + applySeq);
        }
    }

    private void sendCusIndivToRisk(CusIndivVO cusIndivVO, NlsCreditInfoVO nlsCreditInfoVO) {
        // 授信申请流水号
        String applySeq = nlsCreditInfoVO.getLmtApplySeq();
        log.info("优e贷客户建档，发送 个人客户信息 kafka消息给大数据开始执行,流水号:" + applySeq);
        try {
            boolean flag = false;
            //查询开关
            List<NlsStageInfoVO> infoVOS = nlsStageInfoService.queryList();
            for(NlsStageInfoVO vo:infoVOS){
                if(vo.getPrdId().equals("11110004") && vo.getStatus().equals("on") && vo.getStage().equals("credit")){
                    flag = true;
                }
            }
            JSONObject jsonObject = new JSONObject();
            CusIndivNoticeVO cusIndivNoticeVO = new CusIndivNoticeVO();
            cusIndivNoticeVO.setTableName("CUS_INDIV");
            cusIndivNoticeVO.setCusId(cusIndivVO.getCusId());
            cusIndivNoticeVO.setCusName(cusIndivVO.getCusName());
            cusIndivNoticeVO.setCertType(cusIndivVO.getCertType());
            cusIndivNoticeVO.setCertCode(cusIndivVO.getCertCode());
            cusIndivNoticeVO.setCreateTime(cusIndivVO.getCreateTime());
            //数据日期
            String timeStamp = TimeUtil.getTimeStampByPattern("yyyy-MM-dd HH:mm:ss");
            cusIndivNoticeVO.setDataTime(timeStamp);

            KafkaNoticeHeader header = new KafkaNoticeHeader();
            header.setMessageCode("YED_JISHI");
            header.setTimestamp(timeStamp);
            header.setTransactionId(getTransactionId());
            header.setSysName("netLoan");

            jsonObject.put("head", header);
            jsonObject.put("biz", cusIndivNoticeVO);

            if(!flag){
                log.info("实时采集开关未打开！！！");
                return;
            }
            threadPool.add(() -> {
                KafkaUtil kafkaUtil = new KafkaUtil(kafkaServers, kafkaToptic);
                try {
                    kafkaUtil.sendMessage(JSONObject.toJSONString(jsonObject));
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("优e贷客户建档，发送 个人客户信息 kafka消息给大数据失败，流水号：" + applySeq + ",异常信息：" + e.getMessage());
                }
            });
        } catch (Exception e) {
            log.info("优e贷客户建档，发送 个人客户信息 kafka消息给大数据异常，流水号：" + applySeq + ",异常信息：" + e.getMessage());
        } finally {
            log.info("优e贷客户建档，发送 个人客户信息 kafka消息给大数据结束，申请流水号：" + applySeq);
        }
    }

    private void sendToRisk(NlsCreditInfoVO nlsCreditInfoVO) {
        // 授信申请流水号
        String applySeq = nlsCreditInfoVO.getLmtApplySeq();
        log.info("优e贷授信，发送kafka消息给大数据开始执行,流水号:" + applySeq);
        try {
            boolean flag = false;
            //查询开关
            List<NlsStageInfoVO> infoVOS = nlsStageInfoService.queryList();
            for(NlsStageInfoVO vo:infoVOS){
                if(vo.getPrdId().equals("11110004") && vo.getStatus().equals("on") && vo.getStage().equals("credit")){
                    flag = true;
                }
            }
            JSONObject jsonObject = new JSONObject();
            NlsCreditInfoNoticeVO array = new NlsCreditInfoNoticeVO();
            array.setTableName("NLS_CREDIT_INFO");
            //数据日期
            String timeStamp = TimeUtil.getTimeStampByPattern("yyyy-MM-dd HH:mm:ss");
            array.setApprvSts(nlsCreditInfoVO.getApprvSts());
            array.setLmtApplySeq(nlsCreditInfoVO.getLmtApplySeq());
            array.setRefuseCause(nlsCreditInfoVO.getRefuseCause());
            array.setDataTime(timeStamp);

            KafkaNoticeHeader header = new KafkaNoticeHeader();
            header.setMessageCode("YED_JISHI");
            header.setTimestamp(timeStamp);
            header.setTransactionId(getTransactionId());
            header.setSysName("netLoan");

            jsonObject.put("head", header);
            jsonObject.put("biz", array);

            if(!flag){
                log.info("实时采集开关未打开！！！");
                return;
            }
            threadPool.add(() -> {
                KafkaUtil kafkaUtil = new KafkaUtil(kafkaServers, kafkaToptic);
                try {
                    kafkaUtil.sendMessage(JSONObject.toJSONString(jsonObject));
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("优e贷授信，发送kafka消息给大数据失败，流水号：" + applySeq + ",异常信息：" + e.getMessage());
                }
            });
        } catch (Exception e) {
            log.info("优e贷授信，发送kafka消息给大数据异常，流水号：" + applySeq + ",异常信息：" + e.getMessage());
        } finally {
            log.info("优e贷授信，发送kafka消息给大数据结束，申请流水号：" + applySeq);
        }
    }


    /**
     *
     * 获取推荐人信息表
     * @param nlsCreditInfoVO
     * @return
     */
    private CusReferrerInfoVO getCusReferrerInfo( NlsCreditInfoVO nlsCreditInfoVO) throws Exception{
        CusReferrerInfoVO cusVo =new CusReferrerInfoVO();
        cusVo.setLmtApplySeq(nlsCreditInfoVO.getLmtApplySeq());
        CusReferrerInfoVO cusReferrerInfoVO = cusReferrerInfoService.queryChargeoffBrIdByPk(cusVo);
        return cusReferrerInfoVO;
    }

    public static String getTransactionId() {
        String transactionId = "SEQ" + DateFormatUtils.format(new Date(), DateFormatConstant.DATETIME_FORMAT_COMPACT, Locale.CHINA) +
                RandomCodeUtils.generateLetter(6);
        return transactionId;
    }



    @Autowired
    @Qualifier("nlsCreditInfoService")
    private NlsCreditInfoService nlsCreditInfoService;
    @Autowired
    @Qualifier("nlsApplyRelationService")
    private NlsApplyRelationService nlsApplyRelationService;
    @Autowired
    @Qualifier("customerInfoCreateService")
    private CustomerInfoCreateService customerInfoCreateService;
    @Autowired
    @Qualifier("prdInfoService")
    private PrdInfoService prdInfoService;
    @Autowired
    @Qualifier("cusIndivService")
    private CusIndivService cusIndivService;
    @Autowired
    @Qualifier("cusIndivRelService")
    private CusIndivRelService cusIndivRelService;
    @Autowired
    private PatternedLimitableSeqService sequenceService;
    @Autowired
    @Qualifier("companyWhiteListService")
    private CompanyWhiteListService companyWhiteListService;
}
